<template>
  <div class="orders-container">
    <van-nav-bar :title="$t('h.orderPage.pageTitle')" style="background: #ededed" />

    <div class="order-menu-box">
      <van-tabs v-model="active" animated>
        <van-tab title="未完成订单" name="a"></van-tab>
        <van-tab title="历史订单" name="b"></van-tab>
        <van-tab title="取消的订单" name="c"></van-tab>
      </van-tabs>
    </div>

    <div class="order-date-box" v-if="active === 'b'">
      <van-sticky :offset-top="46">
        <van-tabs v-model="dateIndex" animated>
          <van-tab v-for="(date, i) in dateList" :title="date" :key="i"> </van-tab>
        </van-tabs>
      </van-sticky>
    </div>
    <div class="orders-box" v-for="item in !isPaid ? initOrderList : timesLimitList" :key="item.id">
      <div class="orders-content">
        <div class="order-state">
          <div class="order-date">
            <span>{{ item.status }} {{ item.invoice.datetime_close }}</span>
          </div>
          <div class="order-share">
            <van-icon name="share-o" />
            <span>分享</span>
          </div>
        </div>
        <div class="order-content" @click="viewDetail(item)">
          <div class="order-img">
            <div class="img-list" v-for="(img, index) in item.invoice.invoice_line" :key="index">
              <img :src="!img.item.image_thumbnail_cdn ? localImg : img.item.image_thumbnail_cdn" @error="onErrorImg(img)" alt="img" />
            </div>
          </div>
        </div>
        <div class="order-amount">
          <span>${{ item.grand_total || item.invoice.grand_total }}</span>
          <span>X {{ item.invoice.invoice_line | stock }}件</span>
        </div>
      </div>
    </div>
    <div class="bottom-box"></div>

    <van-empty description="暂无订单" v-show="isShowNull || (isPaid && timesLimitList.length === 0)" />
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import moment from 'moment'

export default {
  name: 'Orders',
  data() {
    return {
      isShowNull: true,
      isPaid: true, // 获取的是否是已支付订单列表
      active: 'b',
      params: null, // 向服务器获取订单数据的参数
      voidedOrder: [], // 取消的订单
      dateList: ['今天', '过去7天', '过去30天', '2022', '2021', '2020', '2019', '更多'],
      dateIndex: 0, // 日期索引
      localImg: 'static/img/mxbc/Ice_Cream/Purple_Potato_Latte.jpeg'
    }
  },
  created() {
    var shopsId = JSON.parse(sessionStorage.getItem('license_id'))
    var params = new URLSearchParams()
    params.set('license_id', shopsId)
    this.initDoneOrder(params)
    this.params = params
  },
  // 计算每个订单商品件数
  filters: {
    stock(list) {
      var num = 0
      list.forEach(item => {
        num += item.quantity
      })
      return num
    }
  },
  computed: {
    ...mapState({
      succeedOrder: state => state.account.succeedOrder,
      failedOrder: state => state.account.failedOrder
    }),
    initOrderList() {
      var list = []
      switch (this.active) {
        case 'a':
          list = this.failedOrder
          break
        case 'b':
          list = this.succeedOrder
          break
        default:
          list = this.succeedOrder.filter(item => item.status === 'voided')
      }
      list.forEach(item => {
        var closeTime = item.invoice.datetime_close
        var createTime = item.created_at
        item.invoice.datetime_close = this.$moment.TZ(closeTime)
        item.created_at = this.$moment.TZ(createTime)
      })
      return list
    },
    // 根据时间查看订单
    timesLimitList() {
      var list = this.initOrderList
      var date = this.dateList[this.dateIndex]
      var timer = 0
      var filterList = []
      switch (date) {
        case '今天':
          timer = Date.parse(moment().startOf('day').format())
          break
        case '过去7天':
          timer = Date.parse(moment().subtract(7, 'days').calendar())
          break
        case '过去30天':
          timer = Date.parse(moment().subtract(30, 'days').calendar())
          break
        default:
          timer = Number(date)
          filterList = list.filter(item => new Date(item.invoice.datetime_close).getFullYear() === timer)
          return filterList
      }
      filterList = list.filter(item => Date.parse(item.invoice.datetime_close) > timer)
      return filterList
    }
  },
  watch: {
    // 获取未完成订单
    active(num) {
      if (num === 'a') {
        this.initUndoneOrder(this.params)
        this.isPaid = false
        return
      }
      this.isPaid = true
    },
    // 监听订单列表是否为空
    initOrderList(list) {
      if (list.length > 0) return (this.isShowNull = false)
      this.isShowNull = true
    }
  },
  methods: {
    ...mapActions(['getSucceedOrder', 'getFailedOrder']),
    initDoneOrder(params) {
      this.$load.start()
      this.getSucceedOrder(params).then(msg => {
        if (msg) return this.$msg.danger(msg + ' done_order_err')
        this.$load.done()
      })
    },
    initUndoneOrder(params) {
      this.$load.start()
      this.getFailedOrder(params).then(msg => {
        if (msg) return this.$msg.danger(msg + ' undone_order_err')
        this.$load.done()
      })
    },
    viewDetail(item) {
      this.$router.push({ name: 'orderdetail', params: { item, isPaid: this.isPaid } })
    },
    // 捕获错误图片
    onErrorImg(img) {
      this.$set(img.item, 'image_thumbnail_cdn', this.localImg)
    }
  }
}
</script>

<style lang="less" scoped>
.orders-container {
  position: absolute;
  width: 100%;
  height: 100%;
  max-width: 640px;
  background-color: #ededed;
}

.van-nav-bar {
  position: fixed;
  width: 100%;
  max-width: 640px;
  z-index: 3;
}

/deep/.van-tab {
  background-color: #ededed;
}
/deep/.van-tabs__nav {
  background-color: #ededed;
}
.order-menu-box {
  position: relative;
  max-width: 640px;
  width: 100%;
  left: 50%;
  transform: translateX(-50%);
  top: 46px;
  /deep/.van-tabs__line {
    background-color: #ffbf05;
  }
}
.order-date-box {
  position: relative;
  top: 46px;
  /deep/.van-tabs__line {
    background-color: #ffbf05;
  }
}
.orders-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  top: 54px;
  width: 100%;
  .orders-content {
    width: 97%;
    height: 110px;
    border-radius: 9px;
    background-color: white;
    margin-bottom: 0.45em;
    .order-state {
      position: relative;
      left: 50%;
      transform: translate(-50%);
      display: flex;
      width: 95%;
      height: 25%;
      border-bottom: 0.06em solid #e0e0e0;
      .order-date {
        display: flex;
        align-items: center;
        width: 80%;
        height: 100%;
        span:nth-child(1) {
          overflow: hidden;
          font-size: 0.85em;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
      .order-share {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        width: 20%;
        height: 100%;
        .van-icon-share-o {
          font-size: 1.1em;
          color: #ffbf05;
        }
        span:nth-child(2) {
          color: #ffbf05;
          margin-left: 0.3em;
          font-size: 0.9em;
          white-space: nowrap;
        }
      }
    }
    .order-content {
      position: relative;
      display: flex;
      width: 75%;
      height: 75%;
      overflow-x: scroll;
      margin-left: 2.5%;
      .order-img {
        display: flex;
        align-items: center;
        height: 100%;
        .img-list {
          overflow: hidden;
          width: 60px;
          height: 60px;
          border-radius: 6px;
          margin-right: 0.6em;
          img:nth-child(1) {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
    .order-amount {
      position: absolute;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      right: 1.5%;
      bottom: 0;
      width: 20%;
      height: 75%;
      padding-right: 2.5%;
      span:nth-child(1) {
        font-size: 0.8em;
        margin-top: 0.6em;
      }
      span:nth-child(2) {
        font-size: 0.8em;
      }
    }
  }
}
.bottom-box {
  position: relative;
  top: 46px;
  height: 58px;
}

/deep/ .van-empty {
  margin-top: 3em;
}
</style>
